import React, { useEffect } from 'react';
import { Table, Button } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import axios from 'axios';

const ClassManagement = () => {
    const dispatch = useDispatch();
    const classes = useSelector(state => state.classes);

    useEffect(() => {
        const fetchClasses = async () => {
            const response = await axios.get('/api/classes/');
            dispatch({ type: 'SET_CLASSES', payload: response.data });
        };
        fetchClasses();
    }, [dispatch]);

    const columns = [
        { title: '班级名称', dataIndex: 'name', key: 'name' },
        {
            title: '操作',
            render: (_, record) => (
                <Button type="link" onClick={() => handleDelete(record.id)}>删除</Button>
            ),
        },
    ];

    const handleDelete = async (id) => {
        await axios.delete(`/api/classes/${id}/`);
        const updatedClasses = classes.filter(classes => classes.id !== id);
        dispatch({ type: 'SET_CLASSES', payload: updatedClasses });
    };

    return (
        <div>
            <h1>班级管理</h1>
            <Table dataSource={classes} columns={columns} rowKey="id" />
            <Button type="primary">添加班级</Button>
        </div>
    );
};

export default ClassManagement;
